package com.vgooo.client.myvg;


import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;
import com.vgooo.client.Constants;
import com.vgooo.client.R;
import com.vgooo.client.VGActivity;
import com.vgooo.client.VGApplication;
import com.vgooo.client.ViewLayout;
import com.vgooo.util.BitmapUtils;
import com.vgooo.util.DebugTools;
import com.vgooo.util.Loading;
import com.vgooo.util.Loading.Progress;
import com.vgooo.util.TimeUtils;

public class PhotoActivity extends VGActivity {

	public static final int NONE = 0;
	public static final int PHOTOHRAPH = 1;// 拍照
	public static final int PHOTOZOOM = 2; // 缩放
	public static final int PHOTORESOULT = 3;// 结果

	public static final String IMAGE_UNSPECIFIED = "image/*";
	public static final String className = "PhotoActivity";
	ImageView imageView = null;
	
	AlertDialog dialog ; 
	
	
	String result ;
	
	AlertDialog resultDialog ;
	
	final String photoPath = VGApplication.file + "/userPhoto.JPG";
	
	boolean hasSelect  = false ;
	
	private Context context = this ;
	
	private Progress progress ;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_vg_change_photo);
		
		initView() ;
		
		addListener() ;

	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		// 友盟统计功能，打开页面
		MobclickAgent.onResume(this);
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		// 友盟统计功能，打开页面
		MobclickAgent.onResume(this);
		super.onPause();
	}
	
	public void initView(){
		imageView = (ImageView) findViewById(R.id.my_vg_change_photo_photo);
		
		Builder builder = new Builder(this);
		builder.setTitle("选择照片")
		.setView(getLayoutInflater().inflate(R.layout.my_vg_change_photo_nume, null));
		dialog = builder.create() ;
	
	}

	
	public void addListener(){
	}
	
	
	
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == NONE)
			return;
		// 拍照
		if (requestCode == PHOTOHRAPH) {
			// 设置文件保存路径这里放在跟目录下
			File picture = new File(Environment.getExternalStorageDirectory()
					+ "/temp.jpg");
			System.out.println("------------------------" + picture.getPath());
			startPhotoZoom(Uri.fromFile(picture));
		}

		if (data == null)
			return;

		// 读取相册缩放图片
		if (requestCode == PHOTOZOOM) {
			startPhotoZoom(data.getData());
		}
		// 处理结果
		if (requestCode == PHOTORESOULT) {
			Bundle extras = data.getExtras();
			if (extras != null) {
				Bitmap photo = extras.getParcelable("data");
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 -
																		// 100)压缩文件
				imageView.setImageBitmap(photo);
				try {
					FileOutputStream out = new FileOutputStream(photoPath);
					BufferedOutputStream bos = new BufferedOutputStream(out);
					
					photo.compress(CompressFormat.JPEG, 100, bos);
					DebugTools.log(className ,"存储头像成功：" + BitmapUtils.getImageName(photoPath));
					hasSelect = true ;
					bos.close();
					out.close();
				} catch (IOException e) {
					DebugTools.log(className ,"!!!存储头像失败：" + BitmapUtils.getImageName(photoPath) );
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 64);
		intent.putExtra("outputY", 64);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, PHOTORESOULT);
	}
	
	
	
	Handler handler= new Handler(){
		
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			progress.cancel() ;
			result = (String) msg.obj;
			DebugTools.log(className, "result = " + result) ;
			Builder builder = new Builder(context);
			AlertDialog dialog ;
			View view = LayoutInflater.from(context).inflate(R.layout.chanage_info, null);
			ImageView image = (ImageView) view.findViewById(R.id.chanage_info_image) ;
			switch (msg.what) {
			case Constants.LOAD_SUCCESS:
				DebugTools.log(className,  "上传成功 result =  " + result );
				image.setImageResource(R.drawable.chanage_success);
				
				Toast.makeText(context, "上传成功！" + result , Toast.LENGTH_LONG).show();
				ViewLayout.setViewBack();
				break;
			case Constants.LOAD_FAIL:
				DebugTools.log(className,  "上传失败 result " + result );
				image.setImageResource(R.drawable.chanage_fail);
				Toast.makeText(context, "上传失败！"  + result , Toast.LENGTH_LONG).show();
				break;
			default:
				break;
			}
			builder.setView(view);
			dialog = builder.create() ;
			dialog.show() ;
			TimeUtils.TimeTask(dialog, 800) ;
		}
		
	};
	/*
	 * 上传头像
	 */
	private void uploadPhote(){
		
		UserUtils.uploadFace(photoPath, this, handler);
	}
	
	public void doClick(View v){
		switch (v.getId()) {
		case R.id.my_vg_change_photo_fromCam://拍照
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
					Environment.getExternalStorageDirectory(), "temp.jpg")));
			System.out.println("=============" + Environment.getExternalStorageDirectory());
			startActivityForResult(intent, PHOTOHRAPH);
			dialog.cancel() ;
			break;
		case R.id.my_vg_change_photo_fromPho://相册
			Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT, null);
			intent2.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
					IMAGE_UNSPECIFIED);
			startActivityForResult(intent2, PHOTOZOOM);
			dialog.cancel() ;
			break;
			
			
		case R.id.my_vg_change_photo_select://选择照片
			dialog.show();
			break ;
			
			
		case R.id.my_vg_change_photo_upload://上传头像
			if(hasSelect){
				progress = Loading.startProgress(cparent) ;
				uploadPhote();
			}else{
				dialog.show() ;
			}
			break ;

		default:
			break;
		}
		
	}
	
	
}
